import os
from pathlib import Path
from django.core.management.base import BaseCommand
from django.conf import settings
from media.models import File

class Command(BaseCommand):
    help = 'Cleanup unused files in media upload directory'

    def handle(self, *args, **options):
        # Get the upload directory path
        upload_dir = Path(settings.MEDIA_ROOT) / settings.MEDIA_UPLOAD_REL_PATH
        
        if not upload_dir.exists():
            self.stdout.write(self.style.WARNING(f'Upload directory {upload_dir} does not exist'))
            return

        # Get all valid file paths from the database
        valid_paths = set()
        for file_obj in File.objects.all():
            if file_obj.file:
                # Convert to absolute path for comparison
                valid_paths.add(Path(file_obj.file.path).resolve())

        # Walk through the upload directory
        files_deleted = 0
        dirs_deleted = 0
        
        for root, dirs, files in os.walk(upload_dir, topdown=False):
            # Delete files not in database
            for name in files:
                file_path = Path(os.path.join(root, name)).resolve()
                if file_path not in valid_paths:
                    try:
                        os.unlink(file_path)
                        files_deleted += 1
                        self.stdout.write(f'Deleted file: {file_path}')
                    except OSError as e:
                        self.stdout.write(self.style.ERROR(f'Error deleting file {file_path}: {e}'))

            # Try to delete empty directories
            for name in dirs:
                dir_path = os.path.join(root, name)
                try:
                    # Will only succeed if directory is empty
                    os.rmdir(dir_path)
                    dirs_deleted += 1
                    self.stdout.write(f'Deleted empty directory: {dir_path}')
                except OSError:
                    # Directory not empty or other error, skip it
                    pass
        self.stdout.write(self.style.SUCCESS(
            f'Cleanup complete. Deleted {files_deleted} files and {dirs_deleted} empty directories.'
        ))
